package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.mapper.ConversationMapper;
import com.graduation.springbootinit.model.entity.ShopPart.Conversation;
import com.graduation.springbootinit.model.entity.ShopPart.Message;
import com.graduation.springbootinit.service.ConversationService;
import com.graduation.springbootinit.service.MessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

@Service
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements ConversationService {

    @Resource
    private MessageService messageService;

    @Override
    public List<Conversation> getUserConversations(Long userId, boolean isStore) {
        LambdaQueryWrapper<Conversation> wrapper = new LambdaQueryWrapper<>();
        if (isStore) {
            wrapper.eq(Conversation::getStoreId, userId);
        } else {
            wrapper.eq(Conversation::getUserId, userId);
        }
        wrapper.orderByDesc(Conversation::getLastMessageTime);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Conversation getOrCreateConversation(Long userId, String userName, Long storeId, String storeName) {
        LambdaQueryWrapper<Conversation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Conversation::getUserId, userId)
                .eq(Conversation::getStoreId, storeId);
        
        Conversation conversation = this.getOne(wrapper);
        if (conversation == null) {
            // 创建新对话
            conversation = new Conversation();
            conversation.setUserId(userId);
            conversation.setUserName(userName);
            conversation.setStoreId(storeId);
            conversation.setStoreName(storeName);
            conversation.setUserUnreadCount(0);
            conversation.setStoreUnreadCount(0);
            conversation.setLastMessageTime(new Date());
            this.save(conversation);
        }
        
        // 获取消息历史
        List<Message> messages = messageService.getHistoryMessages(conversation.getId(), 20, null);
        
        // 分类消息
        List<Message> userMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 0)
            .collect(Collectors.toList());
        List<Message> storeMsgs = messages.stream()
            .filter(msg -> msg.getSenderType() == 1)
            .collect(Collectors.toList());
        
        // 设置消息列表
        conversation.setUserMessages(userMsgs);
        conversation.setStoreMessages(storeMsgs);
        conversation.setAllMessages(messages);
        
        return conversation;
    }

    @Override
    public void updateLastMessage(Long conversationId, String lastMessage, Integer senderType) {
        Conversation conversation = this.getById(conversationId);
        if (conversation != null) {
            conversation.setLastMessage(lastMessage);
            conversation.setLastMessageTime(new Date());
            this.updateById(conversation);
        }
    }

    @Override
    public void incrementUnreadCount(Long conversationId, boolean isStore) {
        Conversation conversation = this.getById(conversationId);
        if (conversation != null) {
            if (isStore) {
                conversation.setUserUnreadCount(conversation.getUserUnreadCount() + 1);
            } else {
                conversation.setStoreUnreadCount(conversation.getStoreUnreadCount() + 1);
            }
            this.updateById(conversation);
        }
    }

    @Override
    public void markAsRead(Long conversationId, boolean isStore) {
        Conversation conversation = this.getById(conversationId);
        if (conversation != null) {
            if (isStore) {
                conversation.setStoreUnreadCount(0);
            } else {
                conversation.setUserUnreadCount(0);
            }
            this.updateById(conversation);
        }
    }

    /**
     * 发送消息并更新会话状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message sendMessage(Long conversationId, Long senderId, Integer senderType, String content, Integer type) {
        // 创建消息
        Message message = messageService.createMessage(conversationId, senderId, senderType, content, type);
        
        // 更新会话的最后一条消息
        this.updateLastMessage(conversationId, content, senderType);
        // 增加未读计数
        this.incrementUnreadCount(conversationId, senderType == 0);
        
        return message;
    }
}